import { useTemplate, useUpload } from "@sker/runtime"
import { DependencyContainer, ROOT, Router, md5, toFail, toSuccess, useTransaction } from "@sker/core"
import { SysAttachment } from "@sker/entities"
import { extname, join } from "path"
import useMulterS3 from "@sker/multer-s3"

export const get = async () => {
    await useTemplate({ isDev: true })
}

export const post = async (injector: DependencyContainer) => {
    const router = new Router(injector)
    const { scope, addon } = router;
    const root = injector.resolve(ROOT)
    const setting = require(join(root, 'data', 'setting.json'))
    const upload = setting.upload ? setting.upload : 'local';
    if (upload === 'local') {
        const icon = await useTransaction(async m => {
            const icon = m.create(SysAttachment, {})
            await useUpload((info) => {
                const reg = /^[a-zA-Z0-9\-\.]+$/;
                const ispass = reg.test(info.filename)
                const ext = extname(info.filename)
                if (!ispass) {
                    icon.name = md5(info.filename);
                } else {
                    icon.name = info.filename.replace(ext, '');
                }
                icon.type = info.mimeType;
                icon.bucket = 'local';
                icon.from = 'local';
                icon.tags = [];
                icon.url = `/${scope}/${addon}/${info.filename}`
                icon.hash = md5(JSON.stringify(info))
                return icon.url;
            });
            return icon;
        })
        return toSuccess(icon);
    }
    if (upload === 's3') {
        const icon = await useTransaction(async m => {
            const icon = m.create(SysAttachment, {})
            await useMulterS3(injector, async (s) => {
                const ext = extname(s.originalname)
                icon.hash = s.key;
                icon.name = s.originalname.replace(ext, '');
                icon.type = s.mimetype;
                icon.from = 's3'
                icon.bucket = (s as any).bucket;
                icon.url = s.location;
                icon.tags = [];
            })
            return icon;
        })
        return toSuccess(icon);
    }
    return toFail(`unknown ${upload}`)
}
